package com.openxt.nbzj.event;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * 事件管理器
 * @author honghao
 *
 */
public class EventManager {
	private static EventManager manager = null;
	
	private HashMap<String, List<IEventHandler>> handlers 	  	  = new HashMap<String, List<IEventHandler>>();

	private EventManager(){
	}
	
	public static EventManager instance(){
		if( manager == null )
			manager = new EventManager();
		return manager;
	}
	
	/**
	 * 注册事件处理对象
	 * @param type 事件类型
	 * @param handler 事件处理对象
	 */
	public void addEventHandler(String type, IEventHandler handler){
		List<IEventHandler> handlerList = handlers.get(type);
		if( handlerList == null ){
			handlerList = new ArrayList<IEventHandler>();
			handlers.put(type, handlerList);
		}
		
		if( handlerList.indexOf(handler) == -1 )
			handlerList.add(handler);
	}
	
	/**
	 * 删除事件处理对象
	 * @param type 事件类型
	 * @param handler 事件处理对象
	 */
	public void removeEventHandler(String type, IEventHandler handler){
		List<IEventHandler> handlerList = handlers.get(type);
		if( handlerList != null )
			handlerList.remove(handler);
	}

	/**
	 * 删除事件处理对象
	 * @param type 事件类型
	 */
	public void removeEventHandler(String type){
		List<IEventHandler> handlerList = handlers.get(type);
		if( handlerList != null )
			handlers.remove(type);
	}

	/**
	 * 触发事件
	 * @param event 事件处理对象
	 */
	public void fireEvent(Event event) throws Exception{
		List<IEventHandler> handlerList = handlers.get(event.getType());
		if( handlerList != null ){
			for( Iterator<IEventHandler> iter = handlerList.iterator(); iter.hasNext(); ){
				iter.next().handleEvent(event);
			}
		}
	}
}
